<?php

declare(strict_types=1);

namespace app\yperp\common;

trait Docker
{

    /**
     * docker api
     * @param $url
     * @param string $method
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \RedisException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    static function docker_api($url, $method = "GET")
    {
        // var_dump($url);
        $url = 'http://localhost:2375' . $url;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    /**
     * 容器重启
     */
    static  function docer_containers_restart($containerId)
    {
        return static::docker_api("/containers/{$containerId}/restart", 'POST');
    }

    /**
     * 获取硬气状态
     */
    static function docer_containers_info($containerId)
    {
        return static::docker_api("/containers/{$containerId}/json");
    }

    /**
     * 检查容器是否启动
     */
    static function docer_check_run($containerId)
    {
        $containers = static::docer_containers_info($containerId);
        return ($containers['State']['Status'] == 'running') ? true : false;
    }
}
